package com.ksd.quartz.http;

import java.io.BufferedInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class FileDownloader {
    public static void downloadFile(String fileUrl, String saveDir) {
        try {
            URL url = new URL(fileUrl);
            HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
            httpConn.setRequestMethod("GET");
            httpConn.setConnectTimeout(5000);
            httpConn.setReadTimeout(5000);
            httpConn.connect();

            if (httpConn.getResponseCode() == HttpURLConnection.HTTP_OK) {
                InputStream inputStream = new BufferedInputStream(httpConn.getInputStream());
                FileOutputStream outputStream = new FileOutputStream(saveDir);
                byte[] buffer = new byte[1024];
                int bytesRead;
                while ((bytesRead = inputStream.read(buffer)) != -1) {
                    outputStream.write(buffer, 0, bytesRead);
                }
                outputStream.close();
                inputStream.close();
                System.out.println("文件下载成功: " + saveDir);
            } else {
                System.out.println("下载失败，服务器返回状态码: " + httpConn.getResponseCode());
            }
        } catch (Exception e) {
            System.out.println("下载过程中出现错误: " + e.getMessage());
        }
    }

    public static void main(String[] args) {
        String fileURL = "http://39.106.76.75:9090/update.img";
        String saveDir = "D:\\playservice\\云服务器升级数据\\update.img";// 替换为你希望保存的路径
        downloadFile(fileURL, saveDir);
    }
}